const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const { runCommand } = require('./runCommand')

/**
 * 获取?后的参数
 * @param {*} value 字符串 如呵呵?install=1&version=1.1.0
 * @returns 对象
 */
function getRequest(value) {
  value = '?' + value.split('?')[1]
  let theRequest = new Object();
  if (value.indexOf("?") != -1) {  
    let str = value.substr(1);  
     let strs = str.split("&");  
     for(var i = 0; i < strs.length; i ++) {  
        theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);  
     }  
  }
  // 去除空值参数
  Object.keys(theRequest).map((item) => {
    if (!theRequest[item] || theRequest[item] == 'undefined') {
      delete theRequest[item]
    }
    return true
  })
  return theRequest;  
}  

/**
 * 递归创建目录 同步方法  
 * @param {*} dirname 需要创建的目录
 * @returns boolean 是否创建成功
 */
function mkdirsSync(dirname) {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (mkdirsSync(path.dirname(dirname))) {
      fs.mkdirSync(dirname);
      return true;
    }
  }
}

/**
 * 读取json文件数据
 * @param {String} jsonFilePath 文件路径
 * @returns json数据
 */
const readJsonFile = (jsonFilePath) => {
  return JSON.parse(fs.readFileSync(jsonFilePath))
}

module.exports = {
  readJsonFile,
  mkdirsSync,
  getRequest
}